import {
  NativeEventEmitter,
  NativeModules,
  AppState,
  PermissionsAndroid,
} from 'react-native';
import wifi from 'react-native-android-wifi';
import {observable, action, computed} from 'mobx';

class WifiStore {
  @observable list = [];
  constructor() {
    this.initWifi();
  }

  initWifi = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          title: 'Wifi networks',
          message: 'We need your permission in order to find wifi networks',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log('Thank you for your permission! :)');
      } else {
        console.log(
          'You will not able to retrieve wifi available networks list',
        );
      }
    } catch (err) {
      console.warn(err);
    }
  };

  isEnable = cb => {
    wifi.isEnabled(isEnabled => {
      if (isEnabled) {
        cb(true);
      } else {
        cb(false);
      }
    });
  };

  setEnabled = enable => {
    wifi.setEnabled(enable);
  };

  connnect = (ssid, password) => {
    // wifi.disconnect();
    wifi.findAndConnect(ssid, password, found => {
      if (found) {
        console.log('wifi is in range');
      } else {
        console.log('wifi is not in range');
      }
    });
  };

  disconnect = () => {
    wifi.disconnect();
  };

  getSSID = cb => {
    wifi.getSSID(ssid => {
      cb(ssid);
    });
  };

  getBSSID = cb => {
    wifi.getBSSID(ssid => {
      cb(ssid);
    });
  };

  loadWifiList = cb => {
    wifi.loadWifiList(
      wifiStringList => {
        this.list = JSON.parse(wifiStringList);
        console.log('list ', this.list);
      },
      error => {
        console.log(error);
      },
    );
  };

  connectionStatus = cb => {
    wifi.connectionStatus(isConnected => {
      cb(isConnected);
    });
  };
}

const wifiStore = new WifiStore();
export default wifiStore;
